#include "usart.h"
#include <stdio.h>

/*****************
 * @brief:usart1初始化
 * @para:void
 * @return:NULL
 *****************/
void usart1_Init(int baudrate)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    
    GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;											//复用推挽输出
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
    
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;											//上拉输入
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
    
    USART_InitTypeDef USART_InitStructure;
    USART_InitStructure.USART_BaudRate = baudrate;											//波特率
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;			//不使用流控
    USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;							//同时开启发送和接收
    USART_InitStructure.USART_Parity = USART_Parity_No;										//校验位
    USART_InitStructure.USART_StopBits = USART_StopBits_1;									//停止位
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;								//字长。不需要校验，所以选8位即可
    USART_Init(USART1, &USART_InitStructure);
    
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);											//开启RXNE标志位到NVIC的输出
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    NVIC_InitTypeDef NVIC_InitSturcture;
    NVIC_InitSturcture.NVIC_IRQChannel = USART1_IRQn;										//中断通道
    NVIC_InitSturcture.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitSturcture.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitSturcture.NVIC_IRQChannelSubPriority = 1;
    NVIC_Init(&NVIC_InitSturcture);
    
    USART_Cmd(USART1, ENABLE);
}

/***************************
 * @brief:usart发送一位数据 按照ASCII对应
 * @para:void
 * @return:NULL
 **************************/
void usart1_sendByte(u8 data)
{
	USART_SendData(USART1, data);
	while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}

/***************************
* @brief:usart数字，将数字转化为字符串，然后逐个发送
 * @para:void
 * @return:NULL
 **************************/
void usart1_sendNum(u32 num)
{
	char buf[32];
	sprintf(buf,"%d",num);
	for(int i = 0;buf[i] != '\0';i++)
	{
		usart1_sendByte(buf[i]);
	}
}

/***************************
 * @brief:usart发送字符串
 * @para:void
 * @return:NULL
 **************************/
void usart1_sendString(char *data)
{
	u8 i;
	for(i = 0;data[i]!= 0;i++)
	{
		usart1_sendByte(data[i]);
	}
}
